package com.miao.websecurity.config;

import com.miao.websecurity.service.RoleApiService;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author MiaoWenqing
 * @description: TODO
 * @date 2021/1/16 19:30
 */
@Component(value = "authService")
public class AuthService {

    @Resource
    private RoleApiService roleApiService;




    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        Object principal = authentication.getPrincipal();
        if (principal instanceof String) {
            String username = (String) principal;
            if ("anonymousUser".equals(username)){

                return false;
            }
            List<String> apiByUserName =this.roleApiService.getApiByAdminId(Integer.parseInt(username));


            //当前访问路径
            String requestURI = request.getRequestURI();
            //通过账号获取资源鉴权
            //根据 username获取可访问的api 集合

            AntPathMatcher antPathMatcher = new AntPathMatcher();
            //检查api权限
            apiByUserName.forEach(System.out::println);
            //检查提交api类型
            return apiByUserName.stream().anyMatch(api -> antPathMatcher.match(api, requestURI));
        }
        return false;
    }
}
